package com.aliengen.thingple.driverapp.ui.activities;

import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import com.aliengen.thingple.driverapp.R;
import com.aliengen.thingple.driverapp.data.models.Anomaly;
import com.aliengen.thingple.driverapp.data.models.CylinderTag;
import com.aliengen.thingple.driverapp.data.models.Report;
import com.aliengen.thingple.driverapp.ui.adapters.CylindersListAdapter;
import com.aliengen.thingple.driverapp.ui.fragments.CylindersListFragment;
import com.sdk.bluetooth.android.BluetoothPrinter;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.FragmentById;
import org.androidannotations.annotations.ViewById;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
@EActivity(R.layout.activity_print_preview)
public class PrintPreviewActivity extends AbstractBaseActivity implements CylindersListFragment.OnListFragmentListener{

    @Extra("report")
    Report report;

    @ViewById
    protected TextView dateTitle;

    @ViewById
    protected TextView truckTitle;

    @ViewById
    protected TextView customerTitle;

    @ViewById
    protected TextView contactTitle;

    @ViewById
    protected TextView customerAddressTitle;

    @ViewById
    protected TextView operationTitle;

    @ViewById
    protected TextView cylindersCount;

    @ViewById
    protected TextView productsList;

    @FragmentById
    CylindersListFragment cylinders_list;

    @AfterViews
    protected void init()
    {
        setTextView(dateTitle, R.string.date, new Date().toString());
        setTextView(truckTitle, R.string.truck_plate_number, report.truck.getPlateNumber());
        setTextView(customerTitle, R.string.customer_name, report.customer.name);
        setTextView(contactTitle, R.string.contact_name, report.customer.contact);
        setTextView(customerAddressTitle, R.string.customer_address, report.customer.address);
        setTextView(operationTitle, R.string.operation_name, report.operation);

        CylindersListAdapter adapter = cylinders_list.getAdapter();

        for(Anomaly anomaly : report.anomalies)
        {
            for(CylinderTag cylinder : report.cylinders) {
                if(anomaly.getCylinder().getReference().compareTo(cylinder.getReference()) == 0)
                {
                    cylinder.setAnomaly(true);
                }
            }
        }

        adapter.updateList(report.cylinders);

        HashMap<String,Integer> list = new HashMap<>();
        List<CylinderTag> anomalies = new LinkedList<>();
        for(CylinderTag cylinder : report.cylinders)
        {
            if(cylinder.isAnomaly())
            {
                anomalies.add(cylinder);
            }
            String gas_type = cylinder.getProductName();
            if(!list.containsKey(gas_type))
            {
                list.put(gas_type, 0);
            }
            Integer number = list.get(gas_type);
            number++;
            list.put(gas_type, number);
        }

        String product_list = "\n";
        for(Map.Entry<String, Integer> gas : list.entrySet())
        {
            String gas_type = gas.getKey();
            Integer quantity = gas.getValue();
            String p = gas_type + "  : " + quantity + "\n";
            product_list += p;
        }

        setTextView(cylindersCount, R.string.cylinders_count, Integer.toString(report.cylinders.size()));

        setTextView(productsList, R.string.products_list, product_list);
        mApplication.update();
    }

    public void onClickPrint(View view){
        BluetoothPrinter printer = mApplication.getPrinter();

        /**
         * Opening the printer.
         */
        if(printer == null)
        {
            showToast("Please connect the bluetooth printer!");
            return;
        }

        if(printer.open() != 0)
        {
            showToast("Printer not available!");
            return;
        }

        printer.setPrinter(10, 5);

        String edtContext = "Thingple DriverApp\n";
        printer.send(edtContext);

        printer.setPrinter(4); // Add new line
        //printer.setPrinter(10, 80);

        /**
         * Report contents.
         */

        printer.send(new Date().toString());
        printer.setPrinter(4);

        byte[] overprinting = { 0x1B, 0x45, 0x01 };
        printer.send(overprinting);

        byte[] charLarge = { 0x1B, 0x4D, 17 };
        printer.send(charLarge);

        printer.send("Truck: " + report.truck.getPlateNumber());
        printer.setPrinter(4);

        printer.send("Delivery Plan:\n" + report.plangroup.plan_reference);
        printer.setPrinter(4);

        printer.send("Customer:\n");
        printer.setPrinter(4);

        try {
            printer.send(report.customer.name.getBytes("GB18030"));
            printer.setPrinter(4);

            printer.send("Contact:\n");
            printer.setPrinter(4);

            printer.send(report.customer.contact.getBytes("GB18030"));
            printer.setPrinter(4);

            printer.send("Address:\n");
            printer.setPrinter(4);

            printer.send(report.customer.address.getBytes("GB18030"));
            printer.setPrinter(4);

        } catch(Exception e)
        {}

        String print = "";
        print += "Operation:\n" + report.operation + "\n";
        print += "Cylinders: " + report.cylinders.size() + "\n";

        printer.send(print);

        HashMap<String,Integer> list = new HashMap<>();
        List<CylinderTag> anomalies = new LinkedList<>();
        for(CylinderTag cylinder : report.cylinders)
        {
            if(cylinder.isAnomaly())
            {
                anomalies.add(cylinder);
            }
            String gas_type = cylinder.getProductName();
            if(!list.containsKey(gas_type))
            {
                list.put(gas_type, 0);
            }
            Integer number = list.get(gas_type);
            number++;
            list.put(gas_type, number);
        }

        for(Map.Entry<String, Integer> gas : list.entrySet())
        {
            String gas_type = gas.getKey();
            Integer quantity = gas.getValue();
            String p = gas_type + "  : " + quantity + "\n";
            printer.send(p);
        }

        if(!anomalies.isEmpty()) {
            String title = "Anomalies:\n";
            printer.send(title);
            for (CylinderTag tag : anomalies) {
                String ref = tag.getReference() + "\n";
                printer.send(ref);
            }
        }

        printer.setPrinter(4);
        printer.send("       Signature:\n");

        // Add new line
        printer.setPrinter(4);
        printer.setPrinter(4);
        printer.setPrinter(4);

        printer.setPrinter(4);
        printer.setPrinter(4);
        printer.setPrinter(4);

        printer.setPrinter(4);
        printer.setPrinter(4);
        printer.setPrinter(4);

        /**
         * Closing the printer.
         */
        if(printer.close() != 0)
        {
            showToast("Unable to close the printer!");
        }
    }

    public void onClickDone(View view){
        Intent nextScreen = new Intent(getApplicationContext(), TruckActivity_.class);
        nextScreen.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(nextScreen);
        this.finish();
    }

    @Override
    public void onListInteraction(CylinderTag item) {

    }
}
